<template>
  <Dialog
    width="1100px"
    :title="id ? '修改商品信息' : '新增商品'"
    :visible.sync="innerVisible">
    <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="110px">
      <Portlet>
        <el-row :gutter="15">
          <div v-if="!id">
            <el-col :span="7">
              <el-form-item label="厂家名称" prop="operation">
                <el-select v-model="model.operation" placeholder="请选择">
                  <el-option label="选择厂家" value="1"></el-option>
                  <el-option label="新增厂家" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5" v-if="model.operation === '1'">
              <el-form-item prop="manufacturersId" label-width="0px">
                <el-select
                  v-model="model.manufacturersId"
                  filterable
                  clearable
                  placeholder="请输入关键词"
                  remote
                  :remote-method="remoteQuery"
                  :loading="cargoOwnerLoading">
                  <el-option
                    v-for="item in cargoOwnerArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5" v-else>
              <el-form-item prop="manufacturersName" label-width="0px">
                <el-input v-model="model.manufacturersName"></el-input>
              </el-form-item>
            </el-col>
          </div>
          <div v-else>
            <el-col :span="12">
              <el-form-item label="厂家名称" prop="manufacturersName">
                <el-input v-model="model.manufacturersName"
                          :disabled="detail.manufacturersName ? true : false"></el-input>
              </el-form-item>
            </el-col>
          </div>

          <el-col :span="12">
            <el-form-item label="商品型号" prop="productNo" :rules="[
                  {required: true, message: '商品编号必须', trigger: 'blur'}
                ]">
              <el-input v-model="model.productNo" :disabled="detail.productNo ? true : false"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName" :rules="[
                  {required: true, message: '商品名称必须', trigger: 'blur'}
                ]">
              <el-input v-model="model.productName" :disabled="detail.productName ? true : false"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品类别:" prop="productCodeArr">
              <product-select ref="productSelect" v-model="model.productCodeArr"
                              :disabled="(detail.bigClassNo && detail.middleClassNo) ? true : false"></product-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="材料类型:" prop="storageTypeCode">
              <el-select v-model="model.storageTypeCode" clearable :disabled="detail.storageTypeCode ? true : false">
                <el-option :key="item.value" v-for="item in storageTypeCodeArr" :label="item.text"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="standard">
              <el-input v-model="model.standard" :disabled="detail.standard? true : false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </Portlet>

      <Portlet title="包件信息">
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label-width="0" prop="packageInfos" :rules="[
          {required: true, message: '包件信息必须', trigger: 'change', type: 'array'}
        ]">
              <PackageTable v-model="model.packageInfos" :original="packageInfos"
                            :isUpdate="id ? true : false"></PackageTable>
            </el-form-item>
          </el-col>
        </el-row>
      </Portlet>

    </el-form>
    <div slot="footer">
      <el-button @click="innerVisible = false">关闭窗口</el-button>
      <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">{{ id ? '保存' : '新增'}}
      </el-button>
    </div>
  </Dialog>
</template>
<script>
import {unixTimestampFilter} from '@/filters'
import {dotData, copy, alert, confirm} from '@/utils'
import {httpGetResponse} from '@/utils/ajax'
import {getSubDictListOfParentCode} from '@/utils/selectOptions'
import PackageTable from '@/views/oms/basicData/manufactorPro/PackageTable'
import L from 'lodash'
export default {
  name: 'AddProductModal',
  components: {
    PackageTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    cargoOwnerId: {
      type: String,
      default: ''
    }
  },
  filters: {
    unixTimestampFilter
  },
  watch: {
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        this.resetFields()
        this.detail = {}
        this.packageInfos = []
        this.model.packageInfos = []
        this.model.manufacturersId = ''
        if (this.id) {
          this.getData()
        }
      }
      this.innerVisible = val
    },
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    }
  },
  data() {
    return {
      innerVisible: this.visible,
      loading: false,
      detail: {},
      packageInfos: [],
      model: {
        manufacturersId: '',
        operation: '1',
        manufacturersName: '',
        productNo: '',
        productName: '',
        productCodeArr: [],
        storageTypeCode: '',
        standard: '',
        packageInfos: []
      },
      storageTypeCodeArr: [],
      cargoOwnerLoading: false,
      cargoOwnerArr: []
    }
  },
  created() {
    getSubDictListOfParentCode('STORAGETYPE').then(arr => {
      this.storageTypeCodeArr = arr
    })
  },
  methods: {
    getData() {
      httpGetResponse('/ms-warehouse-order/basicData/findCargoProductInfo', {id: this.id}).then(response => {
        if (!response.data) {
          return
        }
        let data = dotData(response, 'data') || {}
        this.detail = data
        this.model.manufacturersName = dotData(data, 'manufacturersName')
        this.model.manufacturersId = dotData(data, 'manufacturersId')
        this.model.productNo = dotData(data, 'productOutNo')
        this.model.productName = dotData(data, 'productName')
        this.model.standard = dotData(data, 'standard')
        this.model.storageTypeCode = dotData(data, 'storageTypeCode')
        this.model.productCodeArr = []
        let bigClassNo = dotData(response, 'data.bigClassNo')
        let middleClassNo = dotData(response, 'data.middleClassNo')
        this.model.productCodeArr.push(bigClassNo)
        this.model.productCodeArr.push(middleClassNo)
        this.model.packageInfos = dotData(response, 'data.packageInfos')
        const packageInfos = dotData(response, 'data.packageInfos') || []
        if (Array.isArray(packageInfos)) {
          this.packageInfos = copy(packageInfos.map(v => {
            v.packageName = v.name
            return v
          }), true)
        }
      })
    },
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.productId = this.id
      }
      data.cargoOwnerId = this.cargoOwnerId
      data.bigClassNo = data.productCodeArr[0]
      data.middleClassNo = data.productCodeArr[1]
      delete data.productCodeArr
      data.packageBeanList = data.packageInfos
      delete data.packageInfos
      return this.$ajax.post(url, data)
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '编辑成功' : '新增成功'
        let url = this.id ? '/ms-warehouse-order/basicData/modifyCargoOwnerProduct' : '/ms-warehouse-order/basicData/addCargoOwnerProduct'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm(title, title, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).finally(_ => {
              this.innerVisible = false
              this.resetFields()
              this.loading = false
            })
            this.$emit('refresh', true)
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        this.$refs.elForm.resetFields()
      } catch (err) {
      }
    },
    // 后端搜索
    remoteQuery(query) {
      this.cargoOwnerLoading = true
      this.remoteMethod(query, this)
    },
    // 后端搜索 函数防抖
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      _this.$ajax.get('/ms-warehouse-order/basicData/findManufacturersList', {name: query}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.manufacturersName,
                value: v.id
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000)
  }
}
</script>
